package com.sfc.sdsr.service;

import java.io.IOException;
import java.util.List;

import com.sfc.sdsr.client.ServerAccess;
import com.sfc.sdsr.common.model.Address;
import com.sfc.sdsr.common.model.Event;
import com.sfc.sdsr.common.model.News;
import com.sfc.sdsr.common.model.Person;
import com.sfc.sdsr.common.model.Song;
import com.sfc.sdsr.dao.DaoVerifier;
import com.sfc.sdsr.dao.SqliteDao;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class PullService extends Service implements Runnable {

	private final String TAG = getClass().getSimpleName();
	private Thread selfThread; // for selfThread.interrupt(); at some point
	private String SERVER;
	private int PORT;

	/**
	 * Client adds + Server downloads = Real List local storage in a db somewhere 2 tables per, one client adds and server downloads life span of client adds
	 * will be short, purged as soon as the server download happens server downloads happen every 15 minutes ? maybe all Activities will do a new
	 * intent(PullService.class) this thread will only run while user is activly using app if the user stops using the app, the thread will kill its self, run
	 * will always stopSelf at some point use sqlite3 for db
	 * 
	 * oooh (how to handle) modified data? - flag column in client adds, and treat as add data if local storage modified has a uuid thats not null, take that
	 * uuid and pull that specific id from client adds
	 */
	@Override
	public void run() {
		SharedPreferences sharedPreferences = getSharedPreferences("SfcAppPrefs", MODE_PRIVATE);
		SERVER = sharedPreferences.getString("SERVER", "localhost");
		PORT = sharedPreferences.getInt("PORT", 80);

		DaoVerifier dataVerifier = new DaoVerifier(this, "sfc.db", null, 3);
		SqliteDao sqliteDao = new SqliteDao(this, "sfc.db", null, 3);
		
		ServerAccess serverAccess = new ServerAccess(SERVER, PORT);

		List<Event> events;
		List<Person> people;
		List<Song> songs;
		List<News> news;
		List<Address> addresses;
		
		int iteration = 0;
		boolean condition = true;
		while (condition) {
			Log.d(TAG, "Pull Service Iteration: " + iteration++);
			dataVerifier.ensureDatabaseExist();
			try {
			    Log.d(TAG, "Getting addresses from server (" + SERVER + ")");
			    addresses = serverAccess.getAddresses();
			    sqliteDao.importAddresses(addresses);
			    
			    Log.d(TAG, "Getting members from server (" + SERVER + ")");
                people = serverAccess.getMembers();
                sqliteDao.importPeople(people);
                
				Log.d(TAG, "Getting events from server (" + SERVER + ")");
				events = serverAccess.getEvents();
				sqliteDao.importEvents(events);

				Log.d(TAG, "Getting songs from server (" + SERVER + ")");
				songs = serverAccess.getSongs();
				sqliteDao.importSongs(songs);

				Log.d(TAG, "Getting news from server (" + SERVER + ")");
				news = serverAccess.getNews();
				sqliteDao.importNews(news);

			} catch (IOException ioe) {
				Log.e(TAG, "IO Exception getting info from server (" + SERVER + "): " + ioe.getMessage());
				break;
			}
			try {
				Log.d(TAG, "Sleeping for 10 sec...");
				Thread.sleep(10000);
				Log.d(TAG, "Awake after 10 sec");
			} catch (InterruptedException ie) {
				Log.e(TAG, ie.getMessage(), ie);
			}

			// DEBUG - for now only run once everytime the system loads up and the service isn't runnin in the background
			condition = false;
		}
		stopSelf();
	}

	@Override
	public void onCreate() {
		Log.i(TAG, "Pull Service Starting Up");
		Toast.makeText(this, "Pull Service Starting Up", Toast.LENGTH_SHORT).show();
		selfThread = new Thread(this);
		selfThread.start();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "Request: Pull Service onStartCommand");
		return START_NOT_STICKY;
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "Pull Service Shutting Down");
		Toast.makeText(this, "Pull Service Shutting Down", Toast.LENGTH_SHORT).show();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

}